<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分析室监控列表</title>
    <link rel="stylesheet" href="project/css/first.css">
    <script src="project/js/jquery-1.11.0.min.js" ></script>
    <script src="project/js/jquery-magnet.min.js" ></script>
    <script src="project/js/mock.js" ></script>
</head>
<body>
<div class="container">
    <div class="title">
        <img class="title-img" src="project/img/room.png">
        <div class="room">分析室监控详情</div>
        <div class="deviceNum"></div>
    </div>
    <div id="tool">
        <div class="scale toolBtn" style="margin-right: 20px;padding: 0 10px"></div>
        <div class="control">

            <img src="project/img/big.png" alt="放大" class="control-img" onclick="amplify(1)">
            <span class="control-line">|</span>
            <img src="project/img/lite.png" alt="缩小" class="control-img" onclick="amplify(2)">
        </div>
        <button class="toolBtn" onclick="getTableData()">保存</button>

    </div>
    <div class="main">
        <div class="content">
            <div id="parent">
                <div id="lines">
                    <span class="vert"></span>
                    <span class="hori"></span>
                </div>
                <div id="paper">
                    <div id="canvasBox"></div>
                    <div class="pop pop-tips" style="display: none">
                        <div class="row">
                            本地ip: <span class="ip"></span>
                        </div>
                        <div class="row">
                            cpu利用率: <span class="cpu"></span>
                        </div>
                        <div class="row">
                            内存总量: <span class="memory"></span>
                        </div>
                        <div class="row">
                            当前使用量: <span class="memory_use"></span>
                        </div>
                        <div class="row">
                            硬盘总大小: <span class="disk"></span>
                        </div>
                        <div class="row">
                            当前使用量: <span class="disk_use"></span>
                        </div>
                        <div class="row">
                            当前剩余量: <span class="diskTotalFree"></span>
                        </div>
                        <div class="row">
                            接受的总字节数: <span class="accept"></span>
                        </div>
                        <div class="row">
                            发送的总字节数: <span class="send"></span>
                        </div>
                        <div class="row">
                            当前用户: <span class="user"></span>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
<script>
    //页面缩放
    var pageObj = {
        scale:1
    }
    var scale = 1
    $('.scale').text(pageObj.scale)
    Object.defineProperty(pageObj, 'scale', {
        set: function (val) {
            console.log('发生变化',val)
            $('.scale').text(val)
        },
    })
    var amplify = function (num) {
        if (num == 1) {
            if (scale >= 1.8) {
                return false
            }
            scale = Number((scale + 0.1).toFixed(1))
            changeScale(scale)
        } else {
            if (scale <= 0.3) {
                return false
            }
            scale = Number((scale - 0.1).toFixed(1))
            changeScale(scale)
        }

    }
    var changeScale = function (num) {
        scale = num;
        pageObj.scale = num
        $('.content').css({
            '-webkit-transform': 'scale(' + num + ')',
            '-moz-transform': 'scale(' + num + ')',
            '-ms-transform': 'scale(' + num + ')',
            '-o-transform': 'scale(' + num + ')',
            'transform': 'scale(' + num + ')'
        })
    }
</script>
<script>

    (($) => {
        var myTiming;//鼠标悬浮出弹窗 页面定时器
        const itemBox = {
            width: 130,
            height: 130
        };//定义设备模块大小
        const $window = $(window);
        const $magnet = $.magnet({
            distance: 10,//吸附距离初始值
            stayInParent: false,//固定画布初始值
            alignOuter: true,//外部对其初始值
            alignInner: false,//内部对齐初始值
            alignParentCenter: false,//盒子父级居中对齐
            alignCenter: false,//父级居中对齐
        });

        $window.on('load', () => {
            //页面初始化 设备数据
            // $.ajax({
            //     url: `${ctx}/analysisMonitor/terminalAnalysisRoomInfo/byAnalysisId?roomid=${analysisRoomInfo.id}`,//要请求的服务器url
            //     async: true,//是否是异步请求
            //     cache: true,//是否缓存结果
            //     type: "GET",//请求方式
            //     dataType: "json",//服务器返回什么类型数据 text xml javascript json(javascript对象)
            //     success: function (result) {//函数会在服务器执行成功后执行，result就是服务器返回结果
                    //见下面的代码块

            setTimeout(()=>{
                //todo 创建页面 设备
                if (result.code == '0') {
                    console.log('获取分析师设备信息成功', result)
                    let positionInfo = JSON.parse(result.data.location);
                    let totalList = result.data.totalList?result.data.totalList:[];
                    $('.deviceNum').text(totalList.length + '/台')
                    for (let i = 0; i < positionInfo.length; i++) {
                        for (let j = 0; j < positionInfo[i].childList.length; j++) {
                            for (let z = 0; z < totalList.length; z++) {
                                if (positionInfo[i].childList[j].objData.id == totalList[z].id) {
                                    positionInfo[i].childList[j].objData = {...positionInfo[i].childList[j].objData, ...totalList[z]}
                                }
                            }
                        }
                    }
                    console.log('整合后的数据=', positionInfo)
                    for (let i = 0; i < positionInfo.length; i++) {
                        addBox(positionInfo[i])
                    }
                    addFun()

                }
            },200)


            //     }
            // })
            const $canvasBox = $('#canvasBox');
            const $mask = $('#lines');
            const $horiMagnet = $mask.find('.hori');
            const $vertMagnet = $mask.find('.vert');

            $magnet
                .on('start change end', ({type}) => {
                    console.log(`magnet${type}`);
                })
                .on('end', () => {
                    $horiMagnet.removeClass('show');
                    $vertMagnet.removeClass('show');
                })
                .on('change', (e) => {
                    // show/hide horizon/vertical edge line
                    let result = e.detail;
                    let resultX = result.x;
                    let resultY = result.y;
                    if (resultX) {
                        $vertMagnet.css('left', (resultX.position + 'px'));
                        $vertMagnet.addClass('show');
                    } else {
                        $vertMagnet.removeClass('show');
                    }
                    if (resultY) {
                        $horiMagnet.css('top', (resultY.position + 'px'));
                        $horiMagnet.addClass('show');
                    } else {
                        $horiMagnet.removeClass('show');
                    }
                });


            //初始化设备
            // (function addEle() {
            //     console.log('数据=', deviceJson)
            //     for (let i = 0; i < deviceJson.length; i++) {
            //         addBox(deviceJson[i])
            //     }
            //     addFun()
            // })()

            //创建box
            function addBox(option) {
                const {row, column, childList, name, left, top} = option;
                console.log('创建box传参数', option)
                const rootWidth = $window.width();
                const rootHeight = $window.height();

                const width = (itemBox.width)/scale * column + column * 10; //盒子宽
                const height = (itemBox.height)/scale * row + row * 10 + 20; //盒子高
                //监听dom变化  创建一个链接到回调函数的观察者实例
                var observer = new MutationObserver(function (mutationsList) {
                    mutationsList.forEach(function (item, index) {
                        if (item.type == 'attributes') {
                            if ($(item.target)[0].style.width != width + 'px') {
                                $(item.target)[0].style.width = width + 'px'
                                $(item.target)[0].style.height = Number(height + 10) + 'px'
                            }
                        }
                    });
                })

                //创建 checkbox
                var inset = ''
                const $checkbox = $('<input>')
                    .attr('type', 'checkbox')
                    .prop('checked', false)
                    .on('mousedown touchstart', (evt) => evt.stopPropagation())
                    .on('change', function (e) {
                        if (this.checked) {
                            console.log('兄弟选择器', $(this).next()[0].dataset, 'inset=', inset)
                            let data = $(this).next()[0].dataset
                            inset = inset != '' ? inset : data.top + 'px auto auto ' + data.left + 'px'
                            console.log('inset=', inset)
                            let block = this.parentElement;
                            $(this).next().css({"pointer-events": "none"});
                            $magnet.add(block);
                            $(block)[0].style.width = width + 'px'
                            $(block)[0].style.height = Number(height + 10) + 'px'
                            $(block)[0].style.inset = inset
                        } else {
                            console.log('兄弟选择器', this.parentNode.style.inset)
                            inset = this.parentNode.style.inset
                            let block = this.parentNode;
                            block.style.resize = 'none';//设定用户可调整元素的高度和宽度。
                            $magnet.remove(block);
                            // $(block)[0].style.width = width+'px'
                            // $(block)[0].style.height = Number(height + 10)+'px'
                            $(block)[0].style.inset = inset
                            $(this).next().css({"pointer-events": "auto"});
                            observer.disconnect();
                        }
                    });
                const $block = $('<span>')
                    .css({
                        width: width + 'px',
                        height: Number(height + 10) + `px`,
                        left: left + `px`,
                        top: top + `px`,
                        backgroundColor: `rgba(0, 0, 0, .1)`,
                    })
                    .addClass('block')
                    .on('mousedown', function (e) {
                        this.style.width = width + 'px'
                        this.style.height = Number(height + 10) + 'px'
                        this.style.zIndex = 10;
                        // 开始观察已配置突变的目标节点
                        observer.observe(this, {attributes: true, childList: false, subtree: false});
                    })
                    .on('mouseup', function (e) {
                        observer.disconnect();
                        this.style.width = width + 'px'
                        this.style.height = Number(height + 10) + 'px'
                        this.style.zIndex = 1;
                    })
                    .on('click', function () {
                        $(this).parent().append(this);
                        this.style.zIndex = 1;
                        this.style.width = width + 'px'
                        this.style.height = Number(height + 10) + 'px'
                    })
                    .on('attract unattract attracted unattracted', function (e) {
                        console.log(e.type, e);
                        this.style.width = width + 'px'
                        this.style.height = Number(height + 10) + 'px'
                    })
                    .append($checkbox)
                    .appendTo($canvasBox);

                let parentLength = $("div[class='parent']").length;//当前页面 有几个 parent
                var $parent = $('<div class="parent" data-action="' + name + '"data-top="' + top + '"data-left="' + left + '" data-row="' + row + '" data-column="' + column + '" style="width: ' + Number(column * itemBox.width + column * 10) + 'px;margin-top: 30px;"></div>')
                let A_Z = 'ABCDEFGHIJKLMNOPKRSTUVWXYZ'
                let a_z = 'abcdefghijklmnopkrstuvwxyz'
                for (let i = 0; i < childList.length; i++) {
                    let seachImg = childList[i].objData.id!='' ? childList[i]['objData']['status'] == 1 ? `project/img/on.png` : `project/img/off.png` : `project/img/isnull.png`
                    let onAndOff = childList[i].objData.id!='' ? childList[i]['objData']['status'] == 1 ? 'on' : 'off' : 'isnull'
                    let isRun = childList[i].objData.id!='' ? childList[i]['objData']['status'] == '1' ? '运行中' : '已关机' : '待添加'
                    let id = childList[i].objData.id!='' ? childList[i].objData.id : ''
                    let objname = childList[i].objData.id!='' ? childList[i].objData.name : '- -'
                    let item1 = `<div class="imgbox" data-id="` + id + `">` +
                        `<img class="imgbox-img" src="` + seachImg + `" alt="" >` +
                        ` <div class="status ` + onAndOff + `"><div class="circle"></div>` + isRun + `</div></div>` +
                        `<div class="list_name" data-id="` + id + `">` + objname + `</div> </div>`
                    let haveDom = childList[i].objData ? item1 : ''
                    let str = `<div class="item" data-parent="` + name + `" data-position="` + childList[i].position + `">` + haveDom + `</div>`
                    let $item = $(str)
                    console.log('拥有---------------',str)
                    //添加element

                    $parent.append($item)
                }
                $block.append($parent)
                return $block;
            }

            var Astop = true;
            var Parent = '', toParent = '';

            //添加 设备 拖拽事件
            function addFun() {

                var a_b = false, b_a = false, a_a = false, b_b = false;//定义两个 模块的 插入关系
                $('#canvasBox .item').on('mousedown', function (e) {
                        if (Astop) {
                            if (e.offsetX <= 20 || e.offsetY <= 20) return //防止误操作 故改为距离边框 4 才可进行拖拽操作
                            Parent = $(this)[0].dataset.parent //当前要替换的dom 的 父ID
                            Astop = false;
                            let that = this;
                            let disx = e.offsetX; //获取的拖拽过程的短线的长度（鼠标的位置离盒子边缘的位置）
                            let disy = e.offsetY;
                            let disx2 = e.clientX; //获取的拖拽过程的短线的长度（鼠标的位置离盒子边缘的位置）
                            let disy2 = e.clientY;
                            /*获取当前拖拽的dom的页面位置 begin*/
                            let thatGrandPosition = $(that).parent().parent().position()
                            let thatPosition = $(that).position()
                            let animatePosition = {
                                top: (thatGrandPosition.top + thatPosition.top)/scale,
                                left: (thatGrandPosition.left + thatPosition.left)/scale,
                            }
                            console.log('克隆的互换位置',animatePosition)
                            /*获取当前拖拽的dom的页面位置 end*/
                            let $clone = $(this).clone(); //克隆
                            console.log('克隆的块位置',(e.clientX - e.offsetX)/scale,(e.clientY - e.offsetY)/scale)
                            $clone.addClass('draging').css(animatePosition);
                            $('#canvasBox').append($clone); //追加到box里面
                            $(this).addClass('moving').html(''); //被克隆的元素添加类移除内容
                            $('#canvasBox').on('mousemove', function (e) { //对克隆的盒子进行拖拽
                                $clone.css({
                                    left: (e.pageX - $(this).offset().left)/scale - disx,
                                    top: (e.pageY - $(this).offset().top)/scale - disy
                                })
                                clearTimeout(myTiming);//清除显示定时器
                            });

                            $clone.on('mouseup', function () {
                                    $('#canvasBox').off('mousemove'); //取消mousemove事件
                                    let minValue = 1000; //初始化最小值，用来存储所有盒子的最小值
                                    let minObj;

                                    $('#canvasBox .item').not(':last').each(function () { //不包括克隆的那个盒子
                                        let grandPosition = $(this).parent().parent().position()
                                        let thisPosition = $(this).position()
                                        let smalldistance = Math.sqrt(Math.pow($clone.position().left - thisPosition.left - grandPosition.left, 2) + Math.pow($clone.position().top - thisPosition.top - grandPosition.top, 2)); //利用勾股定理获取每一个盒子离克隆出来的盒子的距离
                                        if (smalldistance < minValue) { //比较
                                            minValue = smalldistance; //获取最小值
                                            minObj = {
                                                dom: $(this),
                                                position: {
                                                    left: (thisPosition.left + grandPosition.left)/scale,
                                                    top: (thisPosition.top + grandPosition.top)/scale,
                                                }
                                            } //距离最短的dom + 定位
                                        }
                                    });
                                    let minData = minObj.dom[0].dataset;//获取距离最短的dom标识
                                    let nowData = $(that)[0].dataset;//获取要拖拽的标识

                                    if ((minData.parent == nowData.parent) && (minData.position == nowData.position)) { //如果当前最小距离的那个盒子和拖拽的盒子索引相等的话，归位。
                                        $clone.animate($(that).position(), 400, function () {
                                            $(that).removeClass('moving').html($clone.html()); //恢复被克隆盒子的相关样式
                                            $(this).remove(); //移除被克隆的盒子
                                            Astop = true;
                                        });
                                    } else {
                                        toParent = minData.parent;//要跳到的div 标识，判断是否是相同div内拖拽
                                        let $minbox = minObj.dom; //最小索引的盒子
                                        let $clone2 = $minbox.clone(); //克隆一个最小盒子的副本，添加相关样式
                                        $clone2.addClass('draging').css({
                                            left: minObj.position.left,
                                            top: minObj.position.top
                                        })
                                        $('#canvasBox').append($clone2); //追加
                                        $minbox.addClass('moving').html('');
                                        $clone.animate(minObj.position, 400, function () { //克隆的内容运动到最小索引的盒子的位置
                                            $minbox.removeClass('moving').html($clone.html()); //移除相关样式，添加内容
                                            $clone.remove(); //移除克隆的盒子
                                            Astop = true;
                                        });
                                        $clone2.animate(animatePosition, 400, function () {
                                                $(that).removeClass('moving').html($clone2.html());
                                                $clone2.remove();
                                                Astop = true;
                                            }
                                        );
                                    }
                                }
                            )
                            ;
                        }
                        return false;
                    }
                )
                ;
                //鼠标悬浮2秒触发弹窗显示
                $(".parent .item").mouseover(function (e) {
                    let left = $(this).offset().left / scale;
                    let top = $(this).offset().top / scale;
                    $(this).addClass('hoverItem')
                    if ($(this)[0].children.length > 0) {
                        let id = $(this)[0].children[0].dataset.id
                        myTiming = setTimeout(function () {
                            //获取 设备信息
                            getTerminalDetailInfoById(id, left, top)

                        }, 1000);
                    }
                });
                $(".item").mouseout(function () {
                    $(this).removeClass('hoverItem')
                    clearTimeout(myTiming);
                    $('.pop').css('display', 'none')
                });
            }

            //获取设备信息
            getTerminalDetailInfoById = function (id, left, top) {
                // $.ajax({
                //     url: `${ctx}/analysisMonitor/terminalAnalysisRoomInfo/getTerminalDetailInfoById?terminalId=` + id,//要请求的服务器url
                //     async: true,//是否是异步请求
                //     cache: true,
                //     type: "GET",//请求方式
                //     dataType: "json",//服务器返回什么类型数据 text xml javascript json(javascript对象)
                //     success: function (result) {//函数会在服务器执行成功后执行，result就是服务器返回结果
                        setTimeout(()=>{
                            if (result2.code == '0') {
                                console.log('获取设备信息成功', result2)
                                popData.ip = result2.data.totalList.localIp
                                popData.memory = result2.data.totalList.memoryTotal
                                popData.memory_use = result2.data.totalList.memoryUsage
                                popData.disk = result2.data.totalList.diskTotal
                                popData.disk_use = result2.data.totalList.diskTotalUsed
                                popData.accept = result2.data.totalList.acceptTotalByte
                                popData.send = result2.data.totalList.sendTotalByte
                                popData.user = result2.data.totalList.issuere
                                popData.cpu = result2.data.totalList.cpuUseRatio
                                popData.diskTotalFree = result2.data.totalList.diskTotalFree
                                $('.pop').css({
                                    display: 'block',
                                    left: left + itemBox.width + 10 + 'px',
                                    top: top + 'px',
                                    zIndex: 99
                                })
                            }
                        },200)
                //     }
                // })
            }

            getTableData = function () {
                let nowDeviceJson = []
                //1.获取页面 class='parant',判断有几个分组
                let $parent = $('#canvasBox .parent')

                //2.获取页面 class='item'
                let $item = $('#canvasBox .item')

                for (let i = 0; i < $parent.length; i++) {
                    let obj = {
                        name: $($parent[i]).data('action'),
                        row: $($parent[i]).data('row'),
                        column: $($parent[i]).data('column'),
                        left: $($parent[i]).parent().position().left,
                        top: $($parent[i]).parent().position().top,
                        zIndex: 1,
                        childList: []
                    }
                    for (let j = 0; j < $item.length; j++) {
                        //根据 data-parent 分别赋值给不同的组
                        if ($($item[j]).data('parent') == obj.name) {
                            let children = $($item[j])[0].children
                            obj.childList.push({
                                position: $($item[j]).data('position'),
                                objData: children.length > 0 ? {
                                    id: children[0].dataset.id,
                                    name: $($($item[j])[0].children[0]).text(),
                                    status: $($($item[j])[0].children[2]).text() == '运行中' ? 1 : 0
                                } : {}
                            })
                        }
                    }
                    nowDeviceJson.push(obj)
                }
                console.log('页面现有表格数据', nowDeviceJson)

                let JsonStr = JSON.stringify(nowDeviceJson)
                console.log('页面现有表格数据 转 json 字符换', JsonStr)
                let formData = new
                    //上传定位信息
                    $.ajax({
                        url: `${ctx}/analysisMonitor/terminalAnalysisRoomInfo/saveLocation`,//要请求的服务器url
                        async: true,//是否是异步请求
                        cache: true,
                        data: {'id': '${analysisRoomInfo.id}', 'location': JsonStr},
                        type: "POST",//请求方式
                        dataType: "json",//服务器返回什么类型数据 text xml javascript json(javascript对象)
                        success: function (result) {//函数会在服务器执行成功后执行，result就是服务器返回结果
                            //见下面的代码块
                            //todo 创建页面 设备
                            if (result.code == '0') {
                                console.log('上传定位信息成功', result)
                                alert('保存数据成功')
                            }

                        }
                    })
            }

            //页面弹窗数据绑定
            var popData = {
                ip: '',
                memory: '',
                memory_use: '',
                disk: '',
                disk_use: '',
                accept: '',
                send: '',
                user: '',
                cpu: '',
                diskTotalFree: ''
            }
            Object.defineProperty(popData, 'ip', {
                set: function (val) {
                    $('.ip').text(val)
                },
            })
            Object.defineProperty(popData, 'memory', {
                set: function (val) {
                    $('.memory').text(val)
                },
            })
            Object.defineProperty(popData, 'memory_use', {
                set: function (val) {
                    $('.memory_use').text(val)
                },
            })
            Object.defineProperty(popData, 'disk', {
                set: function (val) {
                    $('.disk').text(val)
                },
            })
            Object.defineProperty(popData, 'disk_use', {
                set: function (val) {
                    $('.disk_use').text(val)
                },
            })
            Object.defineProperty(popData, 'accept', {
                set: function (val) {
                    $('.accept').text(val)
                },
            })
            Object.defineProperty(popData, 'send', {
                set: function (val) {
                    $('.send').text(val)
                },
            })
            Object.defineProperty(popData, 'user', {
                set: function (val) {
                    $('.user').text(val)
                },
            })
            Object.defineProperty(popData, 'cpu', {
                set: function (val) {
                    $('.cpu').text(val)
                },
            })
            Object.defineProperty(popData, 'diskTotalFree', {
                set: function (val) {
                    $('.diskTotalFree').text(val)
                },
            })
        });
    })(jQuery);
</script>
</body>
</html>